import React, {Component} from 'react';
import {Relax} from 'iflux2';
import {List, Map} from 'immutable';

import {Row, Col, Select, Input, Modal, Tabs} from 'antd';
const Option = Select.Option;
const TabPane = Tabs.TabPane;

import noop from 'util/noop';


@Relax
export default class OrderInfo extends Component {
    static defaultProps = {
        tradeGoodsList: List(),
        ships: List(),
        marketingOrder: Map(),
        invoiceResponseList: List(),
        selfAddress: List(),
        shipId: '',
        shipFee: 0,
        invoiceFee: 0,
        selfId: '',
        invoice: Map(),
        couponId: '',
        integral: '',
        receiptId: '',
        payTypeId: '',
        chooseShippingType: noop,
        setSelfAddressId: noop,
        saveInvoice: noop,
        calculateInvoiceTotal: noop,
        calculateGoodsTotal: noop,
        calculateTradeTotal: noop,
        setMessage: noop
    }


    constructor(props) {
        super(props);

        this.state = {
            invoiceVisible: false,
            selfVisible: false,
            invoiceType: '0',
            invoiceTitle: '',
            errorMsg: ''
        }
    }


    render() {
        const {ships, marketingOrder, invoiceResponseList, shipId, shipFee, selfAddress, selfId, invoiceFee, receiptId
            , payTypeId, calculateInvoiceTotal, calculateGoodsTotal, calculateTradeTotal, setMessage} = this.props;
        const {invoiceVisible, selfVisible, invoiceType, invoiceTitle, errorMsg} = this.state;

        return (
            <Row className="order-info-former">
                <Col span={10}>
                    <div className="pushb">
                        <label className="lh28">给卖家留言：</label>
                        <Input className="w430"
                               maxLength="45"
                               onChange={(e)=>setMessage(e.target.value)}/>
                    </div>
                </Col>
                <Col span={12} offset={2}>
                    <Row className="pushb">
                        <Col span={18}><label className="lh28">商品总价：</label></Col>
                        <Col span={6}>
                            <div className="t-right">&yen;{calculateGoodsTotal().toFixed(2)}</div>
                        </Col>
                    </Row>
                    <Row className="pushb">
                        <Col span={18}><label className="lh28">配送方式：</label>
                            <div className="inline-blk w150">
                                <Select value={shipId.toString()}
                                        placeholder="选择配送方式"
                                        notFoundContent='请先添加配送方式'
                                        onChange={(id)=>this.chooseShippingType(id)}>
                                    {
                                        ships.map((ship, index)=>{
                                            return (
                                                <Option key={index} value={ship.get('id').toString()}>{ship.get('serviceName')}</Option>
                                            )
                                        }).toArray()
                                    }
                                </Select>
                            </div>
                            {
                                ships.filter(ship=>ship.get('id') == shipId).getIn([0, 'serviceType']) == 'self'
                                    ?
                                    <a className="pushl" href="javascript:void(0);" onClick={()=>this.setState({selfVisible: true})}>选择自提地址</a>
                                    : null
                            }
                            {
                                !shipFee && !!receiptId && !payTypeId && <span className="ml10">包邮</span>
                            }
                        </Col>
                        <Col span={6}>
                            <div className="t-right">&yen;{shipFee.toFixed(2)}</div>
                        </Col>
                    </Row>
                    {
                        ships.filter(ship=>ship.get('id') == shipId).getIn([0, 'serviceType']) == 'self' && !!selfId
                            ?
                            <Row className="pushb">
                                <Col span={24}>
                                    <label className="lh28">自提地址：</label>
                                    <div className="inline-blk">
                                        <span>{this.renderSelf()}</span>
                                    </div>
                                </Col>
                            </Row>
                            : null
                    }
                    <Row className="pushb">
                        <Col span={18}><label className="lh28">店铺优惠：</label></Col>
                        <Col span={6}>
                            <div className="t-right">-&yen;{(Math.floor((marketingOrder.get('privilegeValue') || 0) * 100) / 100).toFixed(2)}</div>
                        </Col>
                    </Row>
                    <Row className="pushb">
                        <Col span={18}><label className="lh28">发票信息：</label>
                            {this.renderInvoice()}
                            {
                                invoiceResponseList.filter(invoice=>invoice.get('invoiceType') == 1 || invoice.get('addedTax')).isEmpty()
                                    ?
                                    null
                                    :
                                    <a className="pushl" href="javascript:void(0);" onClick={()=>this.setState({'invoiceVisible': true})}>修改</a>
                            }
                        </Col>
                        <Col span={6}>
                            <div className="t-right">&yen;{calculateInvoiceTotal().toFixed(2)}</div>
                        </Col>
                    </Row>
                    <Row className="pushb">
                        <Col span={18}><label className="lh28">订单总价：</label></Col>
                        <Col span={6}>
                            <div className="t-right t-price font-14">&yen;{calculateTradeTotal().toFixed(2)}</div>
                        </Col>
                    </Row>
                </Col>
                <Modal visible={invoiceVisible}
                       title="发票信息"
                       onOk={this.saveInvoice}
                       onCancel={()=>this.setState({'invoiceVisible': false})}>
                    <Tabs activeKey={invoiceType}
                          type="card"
                          onChange={(invoiceType)=>this.setState({invoiceType})}>
                        <TabPane key="0" tab="不开发票"></TabPane>
                        {
                            invoiceResponseList.filter(invoice=>invoice.get('invoiceType') == 1 || invoice.get('addedTax')).map((invoice, index)=>{
                                let invoiceType = invoice.get('invoiceType');
                                let tab = `${invoiceType == 1 ? '普通发票' : '增值税专用发票'} 税点：${invoice.get('taxPoint')}%`

                                return (
                                    <TabPane key={invoice.get('invoiceType')} tab={tab}>
                                        <Row>
                                            <Col span="3" className="t-center lh-28">发票抬头：</Col>
                                            <Col span="19">
                                                <Input disabled={invoiceType == 2}
                                                       maxLength={50}
                                                       onChange={(e)=>this.setState({invoiceTitle: e.target.value})}
                                                       defaultValue={invoiceType == 2 ? invoice.get('invoiceTitle') : ''}/>
                                            </Col>
                                        </Row>
                                        {
                                            invoiceType == 1 ? <div className="t-red mt5 ml58">{errorMsg}</div> : null
                                        }

                                    </TabPane>
                                )
                            })
                        }
                    </Tabs>
                </Modal>

                <Modal title="选择自提地址"
                       visible={selfVisible}
                       width="620"
                       maskClosable={false}
                       onOk={()=>this.onOk()}
                       onCancel={()=>this.setState({selfVisible: false})}>
                    <div className="pushl">
                        {
                            selfAddress.map((address, index)=>{
                                const {province, area, city, detailAddress, mobilePhone, contactMan, id, fixPhone} = address.toJS();

                                return (
                                    <div key={index} className="pushb">
                                        <input type="radio" name="receipt" className="mr3" value={id}/>
                                        <span className="pushl">{contactMan}</span>
                                        <span className="pushl">{`${province} ${city || ''} ${area || ''}`}</span>
                                        <span className="pushl">{detailAddress}</span>
                                        <span className="pushl">{mobilePhone || fixPhone || ''}</span>
                                    </div>
                                )
                            }).toArray()
                        }
                    </div>
                </Modal>
            </Row>
        )
    }


    saveInvoice = ()=>{
        const {invoiceResponseList} = this.props;
        const {invoiceType, invoiceTitle} = this.state;
        let title = invoiceTitle;
        if (invoiceType == 0) {
            title = "";
        } else if (invoiceType == 2) {
            title = invoiceResponseList.find(invoice=>invoice.get('invoiceType') ==2 ).get('invoiceTitle');
        }else if (invoiceType == 1 && (!invoiceTitle || !invoiceTitle.trim())) {
            this.setState({
                errorMsg: '请输入发票抬头'
            });
            return ;
        }
        this.props.saveInvoice({invoiceType, invoiceTitle: title})
        this.setState({
            invoiceVisible: false,
            errorMsg: ''})
    }


    renderInvoice() {
        const {invoiceType, invoiceTitle} = this.props.invoice.toJS();
        if (!invoiceType || invoiceType == 0) {
            return (
                <span className="t-grayer">不开发票</span>
            )
        } else {
            return <span>{invoiceTitle}({invoiceType == 1 ? '普通发票' : '增值税发票'})</span>
        }
    }


    onOk() {
        let selfId = $("input[name='receipt']:checked").val();

        !!selfId && this.props.setSelfAddressId(selfId);
        this.setState({
            selfVisible: false
        })
    }


    setSelfAddressId(id) {
        this.props.setSelfAddressId(id);
    }


    renderSelf() {
        const {selfAddress, selfId} = this.props;

        const selfs = selfAddress.filter(address=>address.get('id') == selfId);
        if (!selfs.isEmpty()) {
            const {province, area, city, detailAddress, mobilePhone, contactMan, fixPhone} = selfs.get(0).toJS();

            return `${contactMan}, ${province} ${city || ''} ${area || ''} ${detailAddress}, ${mobilePhone || fixPhone || ''}`;
        }
        return '';
    }


    calculateTotalPrice() {
        return this.props.tradeGoodsList.reduce((total, item) => {
            let goods = item.get('goods');
            let {buyCount, price} = goods.toJS();

            return total + (buyCount || 0) * (price || 0);
        }, 0)
    }


    chooseShippingType(id) {
        this.props.chooseShippingType(id);
    }
}